/**
 * @date 2022/4/1
 * @description request封装
 * @author 
 */

import axios from 'axios'
import { netConfig } from '@/config/net.config'
const { contentType, invalidCode, noPermissionCode, requestTimeout, successCode } = netConfig
import store from '@/store/index.js'
import router from '@/router/index.js'
import { ElMessage } from 'element-plus'
import { setting } from '@/config/setting'
const { tokenName } = setting
import { sessionstorage } from '@/utils/storage'
import { resetMessage } from '@/utils/resetMessage.js'

let tokenLose = true

const isDev = process.env.NODE_ENV === 'development'

/**
 * @description 处理code异常
 * @param {*} status
 * @param {*} message
 */

const handleCode = (status, message) => {
    switch (status) {
        case 40301:
            store.dispatch('user/logOut').then(async (res) => {
                console.log(res, '----codeyichang')
                if (res == 200) {
                    await router.push({ path: `/login` }).catch(() => { })
                }
            })
            break
        default:
            // console.log("---");
            // ElMessage.error(msg || `后端接口${code}异常`);
            break
    }
}

const instance = axios.create({
    // baseURL: isDev ? "http://localhost:8080/api" : "",
    timeout: requestTimeout,
    headers: {
        'Content-Type': contentType,
    },
})

//添加请求拦截器: 这是向后台服务器发起的ajax请求
instance.interceptors.request.use(
    (config) => {
        if (store.getters['user/token']) {
            config.headers['authorization'] = store.getters['user/token']
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)
// 添加响应拦截器：后端返回的数据
instance.interceptors.response.use(
    (response) => {
        const res = response.data
        const { data } = response
        const { status, message } = data
        // 操作成功
        if (successCode.indexOf(status) !== -1) {
            return data
        } else if (data.type === 'application/force-download') {
            return data

        } else if (data.type === 'application/vnd.ms-excel') {
            return data
        } else if (data.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            return data
        } else {
            resetMessage.error(message)
            handleCode(status, message)
            return data
        }
    },
    (error) => {
        const { response, msg } = error
        if (error.response && error.response.data) {
            const { status, message } = response.data
            resetMessage.error(message)
            return Promise.reject(error)
        } else {
            console.log('错误的else')
            let { message } = error
            if (message === 'Network Error') {
                message = '后端接口连接异常'
            }
            if (message.includes('timeout')) {
                message = '后端接口请求超时'
            }
            if (message.includes('Request failed with status code')) {
                const code = message.substr(message.length - 3)
                message = '后端接口' + code + '异常'
            }
            resetMessage.error(message || `后端接口未知异常`)
            return Promise.reject(error)
        }
    }
)

export default instance